//
//  THAddOnsTool.m
//  duolaCard
//
//  Created by 希达 on 2018/5/8.
//  Copyright © 2018年 zyy. All rights reserved.
//

#import "THAddonsTool.h"
#import "THImageTool.h"
#import "THColorView.h"
#import "THAddTextView.h"


#import "UIImage+ImageEffects.h"

@interface THAddonsTool() <UIGestureRecognizerDelegate>
@property (weak, nonatomic) THImageTool *textBaseTool;
@property (weak, nonatomic) THImageTool *textPropertyTool;
@property (weak, nonatomic) THColorView *colorView;
@property (weak, nonatomic) THBottomTool *bottomTool;
@property (weak, nonatomic) THAddTextView *addTextView;
@property (copy, nonatomic) NSString *fontName;
@property (strong, nonatomic) UIColor *textColor;
@property (strong, nonatomic) NSMutableArray *colorArray;


@property (strong, nonatomic) UIImage *originalImage;
@property (strong, nonatomic) UIImage *addBgImage;

@property (strong, nonatomic) UIImage *addTextBgImg;
@property (strong, nonatomic) THColorModel *boldModel;
@property (strong, nonatomic) THColorModel *italicModel;
@end

@implementation THAddonsTool


- (void)dealloc {
    NSLog(@"%@释放了", NSStringFromClass(self.class));
}

- (void)setup {
    [super setup];

    _originalImage = [self.editor.imageView.image fixOrientation];

    self.fontName = @"ArialMT";
    self.textColor = [UIColor blackColor];
    self.colorArray = [NSMutableArray array];
    
    [self configColorArray];
    [self configBottomTool];
    [self configTextBaseTool];

    [self affineTransformScale:nil toView:self.bgView isShow:YES];

    /// 提前获取AddTextView 背景图
    self.addTextBgImg = [[self capture:self.editor.view] blurImage];
}

- (void)cleanup {
    [self affineTransformScale:nil toView:self.bgView isShow:NO];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(kTHImageToolAnimationDuration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.bgView removeFromSuperview];
        [self.workingView removeFromSuperview];
    });
}

// 文字
- (void)configTextBaseTool {
    CGFloat height = self.editor.bgView.tz_height - self.collectionView.tz_height - self.bottomTool.tz_height;
    THImageTool *textBaseTool = [[THImageTool alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.collectionView.frame), self.collectionView.tz_width, height)];
    textBaseTool.imageArray = @[@"text_A"];
    textBaseTool.titleArray = @[@"Text"];
    [textBaseTool configView];
    [self.bgView addSubview:textBaseTool];
    self.textBaseTool = textBaseTool;


    @weakify(self);
    [textBaseTool setBtnClickBlock:^(NSString *title, BOOL isSelect) {
        @strongify(self);
        self.editor.titleName = title;
        [self configTextPropertyTool];
        [self configColorView];
    }];
}

/// 字体
- (void)configTextPropertyTool {
    CGFloat height = self.textBaseTool.tz_height - 30;
    THImageTool *textPropertyTool = [[THImageTool alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.collectionView.frame), self.collectionView.tz_width, height)];
    textPropertyTool.imageArray = @[@"text_B_def", @"text_I_def"];
    textPropertyTool.imageSelectArr = @[@"text_B_sel", @"text_I_sel"];
    textPropertyTool.titleArray = @[@"Bold", @"Italic"];
    textPropertyTool.isSelect = YES;
    [textPropertyTool configView];
    [self.bgView addSubview:textPropertyTool];
    self.textPropertyTool = textPropertyTool;

    [self.bottomTool showDoneBtn];
    [self affineTransformScale:self.textBaseTool toView:self.textPropertyTool isShow:YES];

    @weakify(self);
    [textPropertyTool setBtnClickBlock:^(NSString *title, BOOL isSelect) {
        @strongify(self);
        if ([title isEqualToString:@"Bold"]) {
            if (isSelect) {
                if ([self.fontName containsString:@"Italic"]) {
                    self.fontName = [self.fontName stringByReplacingOccurrencesOfString:@"-Italic" withString:@"-BoldItalic"];
                } else {
                    self.fontName = [self.fontName stringByReplacingOccurrencesOfString:@"MT" withString:@"-BoldMT"];
                }
            } else {
                if ([self.fontName containsString:@"Italic"]) {
                    self.fontName = [self.fontName stringByReplacingOccurrencesOfString:@"Bold" withString:@""];
                } else {
                    self.fontName =[self.fontName stringByReplacingOccurrencesOfString:@"-Bold" withString:@""];
                }
            }
            self.boldModel.isSelected = isSelect;
        } else {
            if (isSelect) {
                if ([self.fontName containsString:@"Bold"]) {
                    self.fontName = [self.fontName stringByReplacingOccurrencesOfString:@"-Bold" withString:@"-BoldItalic"];
                } else {
                    self.fontName = [self.fontName stringByReplacingOccurrencesOfString:@"MT" withString:@"-ItalicMT"];
                }
            } else {
                if ([self.fontName containsString:@"Bold"]) {
                    self.fontName = [self.fontName stringByReplacingOccurrencesOfString:@"Italic" withString:@""];
                } else {
                    self.fontName =[self.fontName stringByReplacingOccurrencesOfString:@"-Italic" withString:@""];
                }
            }
            self.italicModel.isSelected = isSelect;
        }
        self.boldModel.colorName = self.fontName;
        self.italicModel.colorName = self.fontName;
        NSLog(@"fontName == %@", self.fontName);
        [self configAddTextViewWithText:nil];
    }];
}

// 底部按钮
- (void)configBottomTool {
    CGFloat heigth = 44 + (TZCommonTools.tz_isIPhoneX ? 34 : 0);
    CGFloat top = self.editor.bgView.tz_height - heigth;
    THBottomTool *bottomTool = [[THBottomTool alloc] initWithFrame:CGRectMake(0, top, self.editor.bgView.width, heigth)];
    [self.bgView addSubview:bottomTool];
    self.bottomTool = bottomTool;

    @weakify(self);
    [bottomTool setDidBottomCancelBtnClickBlock:^{
        @strongify(self)
        self.editor.titleName = @"Add-ons";
        [self.bottomTool hiddenDoneBtn];
        [self affineTransformScale:self.textBaseTool toView:self.textPropertyTool isShow:NO];
        [self affineTransformScale:nil toView:self.colorView isShow:NO];

        [self removeAddTextLbl];
        self.editor.imageView.image = self.originalImage;
        self.bottomTool.leftTitle = @"Back";
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(kTHImageToolAnimationDuration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.textPropertyTool removeFromSuperview];
            [self.colorView removeFromSuperview];
        });
    }];

    [bottomTool setDidBottomDoneBtnClickBlock:^{
        @strongify(self)
        self.editor.titleName = @"";
        [self affineTransformScale:nil toView:self.colorView isShow:NO];
        
        UIImage *image = [self buildImage:self.editor.imageView.image];
        self.editor.imageView.image = image;
        
        [self removeAddTextLbl];
        [self.editor refreshTool];
    }];

    [bottomTool setDidBottomBackBtnClickBlock:^{
        @strongify(self)
        self.editor.titleName = @"";
        self.editor.imageView.image = self.originalImage;
        [self.editor refreshTool];
    }];
}

//获取屏幕截屏方法
- (UIImage *)interception {
    CGFloat ratio = self.editor.ratio;
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(self.editor.imageView.image.size.width / ratio, self.editor.imageView.image.size.height /ratio), NO, self.editor.ratio);
    [self.editor.imageView.image drawInRect:CGRectMake(self.editor.imageView.left / ratio, self.editor.imageView.top / ratio, self.editor.imageView.width / ratio, self.editor.imageView.height / ratio)];
    for (UIView *subView in self.editor.imageView.subviews) {
        UIView *exportView = subView;
        UIImage *textImg = [self _screenshot:exportView orientation:UIDeviceOrientationPortrait usePresentationLayer:YES];
        [textImg drawInRect:CGRectMake(exportView.tz_left / ratio, exportView.tz_top / ratio, exportView.width / ratio, exportView.height / ratio)];

    }
    UIImage *tmp = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return tmp;
}
#pragma mark 绘图
- (UIImage *)_screenshot:(UIView *)view orientation:(UIDeviceOrientation)orientation usePresentationLayer:(BOOL)usePresentationLayer
{
    CGSize size = view.bounds.size;
    CGSize targetSize = CGSizeMake(size.width * view.layer.transformScaleX, size.height * view.layer.transformScaleY);

    UIGraphicsBeginImageContextWithOptions(targetSize, NO, [UIScreen mainScreen].scale);

    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGContextSaveGState(ctx);
    [view drawViewHierarchyInRect:CGRectMake(0, 0, targetSize.width, targetSize.height) afterScreenUpdates:NO];
    CGContextRestoreGState(ctx);

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return image;
}

/// 颜色选择
- (void)configColorView {
    THColorView *colorView = [[THColorView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.textPropertyTool.frame), self.textPropertyTool.tz_width, 30)];
    colorView.isShowFont = NO;
    colorView.colorArray = self.colorArray;
    [self.editor.bgView addSubview:colorView];
    self.colorView = colorView;

    [self affineTransformScale:nil toView:colorView isShow:YES];

    @weakify(self);
    [colorView setTh_collectionViewDidSelectItemBlock:^(THColorModel *model) {
        @strongify(self);
        [self configAddTextViewWithText:nil];
    }];
}

- (void)configColorArray {
    for (int i = 0; i < 12; i ++) {
        THColorModel *model = [[THColorModel alloc] init];
        model.color_icon_sel = [NSString stringWithFormat:@"color_sel_%d", i + 1];
        model.color_icon_def = [NSString stringWithFormat:@"color_def_%d", i + 1];
        model.colorName = i == 0 || i == 1 ? self.fontName : [NSString stringWithFormat:@"%d", i + 1];
        [self.colorArray addObject:model];
        if (i == 0) {
            self.boldModel = model;
        } else if (i == 1) {
            self.italicModel = model;
        }
    }
}

// 图片添加文字
- (void)configTextLbl:(UITextView *)textView {

    self.editor.imageView.userInteractionEnabled = YES;
    CGRect frame = self.editor.imageView.frame;
    UIFont *font = textView.font;
    CGSize size = [textView.text sizeForFont:font size:CGSizeMake(frame.size.width - 10, frame.size.height - 10) mode:NSLineBreakByWordWrapping];
    THAddLabelView *textLbl = [[THAddLabelView alloc] initWithFrame:CGRectMake(frame.size.width * 0.5 - size.width * 0.5, frame.size.height * 0.5 - size.height * 0.5, size.width + 20, size.height + 20)];
    textLbl.text = textView.text;
    textLbl.font = font;
    textLbl.textColor = textView.textColor;
    [self.workingView addSubview:textLbl];
    
    @weakify(self);
    [textLbl setTapGestureClickBlock:^(THAddLabelView *labelView) {
        @strongify(self);
        self.addView = labelView;
        [self configAddTextViewWithText:labelView.text];
    }];
}



- (void)configColorModelWithName:(NSString *)colorName color_icon_sel:(NSString *)color_icon_sel color_icon_def:(NSString *)color_icon_def isSelected:(BOOL)isSelected  {
    THColorModel *model = [[THColorModel alloc] init];
    model.color_icon_sel = color_icon_sel;
    model.color_icon_def = color_icon_def;
    model.colorName = colorName;
    model.isSelected = isSelected;
    [self.colorArray insertObject:model atIndex:0];
}

// 文字输入
- (void)configAddTextViewWithText:(NSString *)text {
    CGRect bounds = [UIScreen mainScreen].bounds;
    THAddTextView *addTextView = [[THAddTextView alloc] initWithFrame:CGRectMake(0, bounds.size.height, bounds.size.width, bounds.size.height)];
    addTextView.text = text;
    addTextView.bgImage = self.addTextBgImg;
    [self.colorArray insertObject:self.italicModel atIndex:0];
    [self.colorArray insertObject:self.boldModel atIndex:0];
    addTextView.colorArray = self.colorArray;
    [self.editor.view addSubview:addTextView];
    self.addTextView = addTextView;

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [UIView animateWithDuration:0.2 animations:^{
            [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationSlide];
            addTextView.top = 0;
        }];
    });

    @weakify(self)
    @weakify(addTextView)
    [addTextView setTh_addTextDoneBtnClickBlock:^(UITextView *textView) {
        @strongify(self)
        @strongify(addTextView)
        
        if (self.addView) {
            [self.addView removeFromSuperview];
        }
        
        self.fontName = textView.font.fontName;
        [self configTextLbl:textView];
        [UIView animateWithDuration:0.2 animations:^{
            addTextView.top = [UIScreen mainScreen].bounds.size.height;
        } completion:^(BOOL finished) {
            NSLog(@"textView.text ===  %@", textView.text);
            [addTextView removeFromSuperview];
            self.colorView.colorArray = self.colorArray;
            [self.textPropertyTool setBtnWithStatus:self.boldModel.isSelected isItalic:self.italicModel.isSelected];
            [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationSlide];
        }];
    }];

    [addTextView setTh_addTextCancelBtnClickBlock:^{
        @strongify(self)
        @strongify(addTextView)
        [UIView animateWithDuration:0.2 animations:^{
            addTextView.top = [UIScreen mainScreen].bounds.size.height;
        } completion:^(BOOL finished) {
            [addTextView removeFromSuperview];
            self.colorView.colorArray = self.colorArray;
            [self.textPropertyTool setBtnWithStatus:self.boldModel.isSelected isItalic:self.italicModel.isSelected];
            [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationSlide];
        }];
    }];
}




//- (UIImage *)getWaterMarkImage: (UIImage *)originalImage andLabel:(UILabel *)label {
//    CGFloat ratio = self.editor.ratio;
//    UIFont *font = [UIFont fontWithName:self.fontName size:label.font.pointSize / ratio];
//    UIColor *color = label.textColor;
//    //原始image的宽高
//    CGFloat viewWidth = originalImage.size.width;
//    CGFloat viewHeight = originalImage.size.height;
//    //为了防止图片失真，绘制区域宽高和原始图片宽高一样
//    UIGraphicsBeginImageContext(CGSizeMake(viewWidth, viewHeight));
//    //先将原始image绘制上
//    [originalImage drawInRect:CGRectMake(0, 0, viewWidth, viewHeight)];
//    //sqrtLength：原始image的对角线length。在水印旋转矩阵中只要矩阵的宽高是原始image的对角线长度，无论旋转多少度都不会有空白。
//    CGFloat sqrtLength = sqrt(viewWidth*viewWidth + viewHeight*viewHeight);
//    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
//    paragraphStyle.alignment = label.textAlignment;
//    //文字的属性
//    NSDictionary *attr = @{NSFontAttributeName: font,
//                           NSForegroundColorAttributeName : color,
//                           NSObliquenessAttributeName: ([self.fontName containsString:@"Oblique"] ? @0.05 : @0),
//                           NSParagraphStyleAttributeName : paragraphStyle
//                           };
//    NSString *mark = label.text;
//    NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:mark attributes:attr];
//    //绘制文字的宽高
//    CGFloat strWidth = label.size.width / ratio;
//    CGFloat strHeight = label.size.height / ratio;
//    //开始旋转上下文矩阵，绘制水印文字
//    CGContextRef context = UIGraphicsGetCurrentContext();
//    CGContextConcatCTM(context, CGAffineTransformIdentity);
//    CGContextConcatCTM(context, label.transform);
//    CGContextConcatCTM(context, CGAffineTransformIdentity);
//
//    CGRect textRect = CGRectMake(label.frame.origin.x / ratio, label.frame.origin.y / ratio , strWidth, strHeight);
//    //将绘制原点恢复初始值，保证当前context中心和源image的中心处在一个点(当前context已经旋转，所以绘制出的任何layer都是倾斜的)
//    [mark drawInRect:textRect withAttributes:attr];
//    //计算需要绘制的列数和行数
////    int horCount = sqrtLength / (strWidth + HORIZONTAL_SPACE) + 1;
////    int verCount = sqrtLength / (strHeight + VERTICAL_SPACE) + 1;
////    //此处计算出需要绘制水印文字的起始点，由于水印区域要大于图片区域所以起点在原有基础上移
////    CGFloat orignX = -(sqrtLength-viewWidth)/2;
////    CGFloat orignY = -(sqrtLength-viewHeight)/2;
////    //在每列绘制时X坐标叠加
////    CGFloat tempOrignX = orignX;
////    //在每行绘制时Y坐标叠加
////    CGFloat tempOrignY = orignY;
////    for (int i = 0; i < horCount * verCount; i++) {
////        [mark drawInRect:CGRectMake(tempOrignX, tempOrignY, strWidth, strHeight) withAttributes:attr];
////        if (i % horCount == 0 && i != 0) {
////            tempOrignX = orignX;
////            tempOrignY += (strHeight + VERTICAL_SPACE);
////        }else{
////            tempOrignX += (strWidth + HORIZONTAL_SPACE);
////        }
////    }
//    //根据上下文制作成图片
//    UIImage *finalImg = UIGraphicsGetImageFromCurrentImageContext();
//    UIGraphicsEndImageContext();
//    CGContextRestoreGState(context);
//    return finalImg;
//}

- (void)removeAddTextLbl {
    for (UIView *view in self.editor.imageView.subviews) {
        if ([view isKindOfClass:[THAddLabelView class]]) {
            THAddLabelView *label = (THAddLabelView*)view;
            [label.timer invalidate];
            label.timer = nil;
            [label removeFromSuperview];
        } else if ([view isKindOfClass:[THAddImageView class]]) {
            [view removeFromSuperview];
        }
    }
}


@end


